<template>
  <div class="orders-container">
    <!-- 页面标题和工具栏 -->
    <div class="page-header">
      <div class="title-container">
        <h2 class="page-title">已完成订单</h2>
        <el-tag type="info">共 {{ total }} 条订单</el-tag>
      </div>
      <div class="actions">
        <el-button type="primary" @click="refreshOrders">刷新数据</el-button>
        <el-button type="success" @click="exportOrders">导出订单</el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="hover">
      <el-form :model="queryParams" label-width="80px" inline>
        <el-form-item label="订单号">
          <el-input v-model="queryParams.number" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="queryParams.userName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="queryParams.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="orders-table" shadow="hover">
      <el-table :data="orderList" border style="width: 100%" v-loading="loading" highlight-current-row>
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="number" label="订单号" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="userName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">
            <span>¥{{ scope.row.totalAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100"></el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180"></el-table-column>
        <el-table-column prop="completionTime" label="完成时间" width="180"></el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
          :page-sizes="[10, 20, 50, 100]" v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize" @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="detailDialogVisible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.number }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentOrder.userName }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
        <el-descriptions-item label="备注信息" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ currentOrder.completionTime }}</el-descriptions-item>
      </el-descriptions>

      <div class="order-items">
        <h3>订单商品</h3>
        <el-table :data="currentOrder.items || []" border stripe>
          <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="productImage" label="商品图片" width="100">
            <template #default="scope">
              <el-image style="width: 60px; height: 60px" :src="getImageUrl(scope.row.productImage)"
                :preview-src-list="[getImageUrl(scope.row.productImage)]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="100">
            <template #default="scope">
              <span>¥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
          <el-table-column prop="subtotal" label="小计" width="120">
            <template #default="scope">
              <span>¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="order-summary">
        <div class="summary-item">
          <span class="label">商品总价：</span>
          <span class="value">¥{{ currentOrder.totalAmount?.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span class="label">运费：</span>
          <span class="value">¥{{ currentOrder.shippingFee?.toFixed(2) || '0.00' }}</span>
        </div>
        <div class="summary-item">
          <span class="label">优惠金额：</span>
          <span class="value">- ¥{{ currentOrder.discount?.toFixed(2) || '0.00' }}</span>
        </div>
        <div class="summary-item total">
          <span class="label">实付金额：</span>
          <span class="value">¥{{ currentOrder.actualAmount?.toFixed(2) }}</span>
        </div>
      </div>

      <div class="dialog-footer" slot="footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/assets/js/api';

// 查询参数
const queryParams = reactive({
  page: 1, // 当前页码
  pageSize: 10, // 每页条数
  number: '', // 订单号
  userName: '', // 客户名称
  status: 'completed', // 订单状态：默认查询已完成订单
  timeRange: null, // 创建时间范围
});

// 订单列表数据
const orderList = ref([]); // 订单列表
const total = ref(0); // 总记录数
const loading = ref(false); // 加载状态
const detailDialogVisible = ref(false); // 详情对话框可见性
const currentOrder = ref({}); // 当前选中的订单 

function getImageUrl(imagePath) {
  return `http://localhost:8080${imagePath}`;
}
// 获取订单列表数据
const getOrderList = async () => {
  loading.value = true;
  try {
    // 处理日期范围
    let params = {
      page: queryParams.page,
      pageSize: queryParams.pageSize,
      number: queryParams.number,
      userName: queryParams.userName,
      status: queryParams.status
    };

    if (queryParams.timeRange && queryParams.timeRange.length === 2) {
      params.startTime = queryParams.timeRange[0];
      params.endTime = queryParams.timeRange[1];
    }

    const response = await api.getAllOrders(params);
    // 确保字段名与后端返回的一致
    orderList.value = response.data.records || [];
    total.value = response.data.total || 0;
  } catch (error) {
    ElMessage.error('获取订单列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 刷新订单列表
const refreshOrders = () => {
  getOrderList();
};

// 搜索按钮点击事件
const handleSearch = () => {
  queryParams.page = 1;
  getOrderList();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.number = '';
  queryParams.userName = '';
  // 不重置状态，保持筛选已完成订单
  queryParams.timeRange = null;
  queryParams.page = 1;
  getOrderList();
};

// 每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getOrderList();
};

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page;
  getOrderList();
};

// 导出订单
const exportOrders = () => {
  ElMessage.success('订单导出成功');
  // 实际导出逻辑需要根据后端API实现
};

// 查看订单详情
const viewOrderDetail = async (row) => {
  try {
    loading.value = true;
    const response = await api.getOrderById(row.number);
    currentOrder.value = response.data || {};
    detailDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取订单状态对应的类型
const getStatusType = (status) => {
  const statusMap = {
    'unpaid': 'warning',     // 待付款
    'paid': 'success',       // 已付款
    'pending': 'primary',    // 待处理
    'shipping': 'info',      // 配送中
    'completed': 'success',  // 已完成
    'cancelled': 'danger',   // 已取消
  };
  return statusMap[status] || 'info';
};

// 获取订单状态对应的文本
const getStatusText = (status) => {
  const statusMap = {
    'unpaid': '待付款',
    'paid': '已付款',
    'pending': '待处理',
    'shipping': '配送中',
    'completed': '已完成',
    'cancelled': '已取消',
  };
  return statusMap[status] || '未知状态';
};

// 页面加载时获取订单列表
onMounted(() => {
  getOrderList();
});
</script>

<style scoped>
@import '@/assets/css/orders.css';
</style>